<template>
  <a-drawer
    :title="title"
    :width="720"
    :visible="visible"
    :wrapStyle="{height: '100%',overflow: 'auto',paddingBottom: '108px'}"
    @close="close"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item label="菜单类型" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-radio-group :disabled="model.id ? true : false" @change="onChangeMenuType" v-decorator="['menuType',{'initialValue':localMenuType}]">
            <a-radio :value="0">一级菜单</a-radio>
            <a-radio :value="1">子菜单</a-radio>
            <a-radio :value="2">按钮/权限</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="menuLabel"
          hasFeedback >
          <a-input placeholder="请输入菜单名称" v-decorator="[ 'name', {rules: [{ required: true, message: '请输入菜单标题!' }]}]"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==0"
          label="上级菜单"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :validate-status="validateStatus"
          :hasFeedback="true"
          :required="true">
          <span slot="help">{{ validateStatus === 'error'?'请选择上级菜单':'&nbsp;&nbsp;' }}</span>
          <tree-select
            style="width:100%"
            :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
            :treeData="treeData"
            v-decorator="['parentId', {}]"
            placeholder="请选择父级菜单"
            @change="handleParentIdChange">
          </tree-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单路径">
          <a-input placeholder="请输入菜单路径" v-decorator="[ 'url',{rules: [{ required: localMenuType!==2, message: '请输入菜单路径!' }]}]"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="前端组件">
          <a-input placeholder="请输入前端组件" v-decorator="[ 'component',{rules: [{ required: true, message: '请输入前端组件!' }]}]"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType===0"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="默认跳转地址">
          <a-input placeholder="请输入路由参数 redirect" v-decorator="[ 'redirect',{}]" />
        </a-form-item>

        <a-form-item
          v-if="localMenuType===2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="授权标识">
          <a-input placeholder="多个用逗号分隔, 如: user:list,user:create" v-decorator="[ 'perms', {}]"/>
        </a-form-item>

        <a-form-item
          v-show="localMenuType===2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="授权策略">
          <dict-select-tag v-decorator="['permsType', {initialValue:1}]" placeholder="请选择授权策略" :type="'radio'" :triggerChange="true" dictCode="global_perms_type"/>
        </a-form-item>

        <a-form-item
          v-show="localMenuType===2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态">
          <dict-select-tag v-decorator="['status', {initialValue:1}]" placeholder="请选择状态" :type="'radio'" :triggerChange="true" dictCode="valid_status"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单图标">
          <a-input placeholder="点击右侧按钮选择图标" v-decorator="['icon']">
            <a-icon slot="addonAfter" type="setting" @click="selectIcons" />
          </a-input>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="排序">
          <a-input-number placeholder="请输入菜单排序" style="width: 200px" v-decorator="[ 'sortNo',{initialValue:1.0}]"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否路由菜单">
          <a-switch checkedChildren="是" unCheckedChildren="否" v-decorator="['route', { valuePropName: 'checked', initialValue: true }]"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="隐藏路由">
          <a-switch checkedChildren="是" unCheckedChildren="否" v-decorator="['hidden', { valuePropName: 'checked', initialValue: false }]"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否缓存路由">
          <a-switch checkedChildren="是" unCheckedChildren="否" v-decorator="['keepAlive', { valuePropName: 'checked', initialValue: false }]"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="聚合路由">
          <a-switch checkedChildren="是" unCheckedChildren="否" v-decorator="['alwaysShow', { valuePropName: 'checked', initialValue: false }]"/>
        </a-form-item>

        <a-form-item
          v-if="localMenuType!==2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="打开方式">
          <a-switch checkedChildren="外部" unCheckedChildren="内部" v-decorator="['internalOrExternal', { valuePropName: 'checked', initialValue: false }]"/>
        </a-form-item>
      </a-form>
    </a-spin>

    <div class="drawer-bottom-button">
      <a-button :style="{marginRight: '8px'}" @click="close">取消</a-button>
      <a-button @click="handleSubmit" type="primary">保存</a-button>
    </div>

    <!-- 选择图标 -->
    <icons @choose="handleIconChoose" @close="handleIconCancel" :iconChooseVisible="iconChooseVisible"></icons>
  </a-drawer>
</template>

<script>
import { apiQueryTreeList, apiAddPermission, apiEditPermission } from '@/api/system'
import { TreeSelect } from 'ant-design-vue'
import pick from 'lodash.pick'
import DictSelectTag from '@/components/dict/DictSelectTag'
import Icons from './icon/Icons'

export default {
  name: 'PermissionModal',
  components: {
    TreeSelect, DictSelectTag, Icons
  },
  data () {
    return {
      title: '',
      visible: false,
      iconChooseVisible: false,
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this),
      menuLabel: '菜单名称',
      localMenuType: 0,
      treeData: [],
      validateStatus: '',
      model: {}
    }
  },
  methods: {
    show (title, record) {
      this.form.resetFields()
      this.model = {}
      this.localMenuType = 0
      this.visible = true
      this.title = title
      if (record) {
        this.model = Object.assign({}, record)
        this.initFormValue(record)
      }
      this.loadTree()
    },
    initFormValue () {
      console.log(this.model)
      this.localMenuType = this.model.menuType
      this.menuLabel = this.model.menuType === 2 ? '按钮/权限' : '菜单名称'
      let fieldsVal = {}
      if (this.model.menuType === 0) {
        fieldsVal = pick(this.model, 'menuType', 'name', 'url', 'component', 'redirect', 'icon', 'sortNo', 'route', 'hidden', 'keepAlive', 'alwaysShow', 'internalOrExternal', 'permsType', 'status')
      } else if (this.model.menuType === 1) {
        fieldsVal = pick(this.model, 'menuType', 'name', 'url', 'component', 'parentId', 'icon', 'sortNo', 'route', 'hidden', 'keepAlive', 'alwaysShow', 'internalOrExternal', 'permsType', 'status')
      } else if (this.model.menuType === 2) {
        fieldsVal = pick(this.model, 'menuType', 'name', 'url', 'parentId', 'perms', 'permsType', 'status')
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldsVal)
      })
    },
    close () {
      this.visible = false
    },
    loadTree () {
      const that = this
      apiQueryTreeList().then((res) => {
        if (res.success) {
          that.treeData = []
          const treeList = res.result.treeList
          for (let a = 0; a < treeList.length; a++) {
            const temp = treeList[a]
            temp.isLeaf = temp.leaf
            that.treeData.push(temp)
          }
        }
      })
    },
    onChangeMenuType (e) {
      this.localMenuType = e.target.value
      if (e.target.value === 2) {
        this.menuLabel = '按钮/权限'
      } else {
        this.menuLabel = '菜单名称'
      }
      // this.$nextTick(() => {
      //   this.form.validateFields(['url', 'component'], { force: true })
      // })
    },
    handleParentIdChange (value) {
      if (!value) {
        this.validateStatus = 'error'
      } else {
        this.validateStatus = 'success'
      }
    },
    selectIcons () {
      this.iconChooseVisible = true
    },
    handleIconCancel () {
      this.iconChooseVisible = false
    },
    handleIconChoose (value) {
      this.form.setFieldsValue({ icon: value })
      this.iconChooseVisible = false
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values)
          const formData = Object.assign(this.model, values)
          let obj
          this.confirmLoading = true
          if (!this.model.id) {
            obj = apiAddPermission(formData)
          } else {
            obj = apiEditPermission(formData)
          }
          obj.then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.$emit('ok')
              this.close()
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.drawer-bottom-button {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
}

</style>
